#include "sysmonitor/resources_monitor.hpp"
#include <stdexcept>
#include <iostream>

namespace sysmonitor {

ResourcesMonitor::ResourcesMonitor(const MonitorConfig& config, std::function<void(const SystemResources&)> callback)
    : m_config(config)
    , m_updateCallback(callback) {
    // 初始化CPU信息（只需获取一次）
    m_cpuInfo = cpu::getCpuInfo();
    // 初始化前一次CPU时间（用于首次计算使用率）
    m_previousCpuTimes = cpu::getCpuTimes();
    // 初始化网络监控器，让它获取第一次的流量数据
    m_networkMonitor.calculateTrafficRates();
}

ResourcesMonitor::~ResourcesMonitor() {
    stopMonitoring();
}

void ResourcesMonitor::setUpdateCallback(std::function<void(const SystemResources&)> callback) {
    m_updateCallback = callback;
}

void ResourcesMonitor::startMonitoring() {
    if (m_isRunning) {
        return; // 已经在监控中
    }
  
    m_shouldStop = false;
    m_monitoringThread = std::thread(&ResourcesMonitor::monitoringLoop, this);
    m_isRunning = true;
}

void ResourcesMonitor::stopMonitoring() {
    if (!m_isRunning) {
        return; // 未在监控中
    }
  
    m_shouldStop = true;
    if (m_monitoringThread.joinable()) {
        m_monitoringThread.join();
    }
    m_isRunning = false;
}

const cpu::CpuInfo& ResourcesMonitor::getCpuInfo() const {
    return m_cpuInfo;
}

SystemResources ResourcesMonitor::getCurrentResources() {
    SystemResources resources;
    resources.timestamp = std::chrono::system_clock::now();
  
    // 收集CPU使用率
    if (m_config.monitorCPU) {
        auto currentCpuTimes = cpu::getCpuTimes();
        resources.cpuUsage = cpu::calculateCpuUsage(currentCpuTimes, m_previousCpuTimes);
        m_previousCpuTimes = currentCpuTimes; // 更新前一次CPU时间
    }
  
    // 收集内存信息
    if (m_config.monitorMemory) {
        resources.memoryInfo = memory::getSystemMemoryInfo();
    }
  
    // 收集磁盘信息
    if (m_config.monitorDisk) {
        resources.diskPartitions = filesystem::getDiskPartitions();
    }
  
    // 收集网络流量
    if (m_config.monitorNetwork) {
        resources.networkTraffic = m_networkMonitor.calculateTrafficRates();
    }
  
    return resources;
}

void ResourcesMonitor::monitoringLoop() {
    try {
        while (!m_shouldStop) {
            SystemResources resources = getCurrentResources();
            // 调用回调函数（如果已设置）
            if (m_updateCallback) {
                m_updateCallback(resources);
            }
          
            // 等待更新间隔
            auto next_run = std::chrono::steady_clock::now() + m_config.updateInterval;
            while (std::chrono::steady_clock::now() < next_run) {
                if (m_shouldStop) break;
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }
        }
    } catch (const std::exception& e) {
        std::cerr << "Monitoring loop error: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "Unknown error in monitoring loop" << std::endl;
    }
}


bool ResourcesMonitor::isRunning() const {
    return m_isRunning.load();
}

} // namespace sysmonitor
